#include "entity.h"
#include "../global/defines.h"
#include <QVariant>
#include <QTimer>
#include <QKeyEvent>
#include "../aurasim.h"
#include <QGraphicsScene>
#include <QGraphicsObject>
#include <QDebug>

Entity::Entity(QGraphicsItem *parent) :
    QGraphicsObject(parent),
    mId(-1),
    mAboutClicked(false),
    mCanCopy(false),
    mRemove(false),
    mCanRemove(true),
    mHasCurrent(false)
{
    setName("Entity");
    setFlags(ItemIsSelectable | ItemIsMovable | ItemClipsToShape);
    setAcceptHoverEvents(true);
    setAcceptedMouseButtons(Qt::LeftButton);
    setAcceptDrops(false);
}

ComponentList Entity::components()
{
    return mComponents;
}

int Entity::id()
{
    return mId;
}

void Entity::setID(const int &id)
{
    mId = id;
}

bool Entity::isValid()
{
    return (mId != -1);
}

void Entity::addComponent(QSharedPointer<Component> com)
{
    mComponents.append(com);
}

QJsonObject Entity::toJsonObject()
{
    QJsonObject obj;
    obj.insert("name", name());
    obj.insert("x", pos().x());
    obj.insert("y", pos().y());
    obj.insert("id", id());
    if(parentObject()) {
        Entity* e = static_cast<Entity*>(parentObject());
        obj.insert("pid", e->id());
    }
    return obj;
}

QPainterPath Entity::shape() const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}

void Entity::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(painter)
    Q_UNUSED(option)
    Q_UNUSED(widget)
}

void Entity::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    update();
    QGraphicsItem::mousePressEvent(event);
    mAboutClicked = true;
    QTimer::singleShot(300, [=] {
        mAboutClicked = false;
    });
}

void Entity::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    update();
    QGraphicsItem::mouseMoveEvent(event);
}

void Entity::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    update();
    QGraphicsItem::mouseReleaseEvent(event);
    if(mAboutClicked) {
        emit clicked();
        mAboutClicked = false;
    }
}

QVariant Entity::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
    if(change == QGraphicsItem::ItemSelectedChange) {
        if(value.toInt() == 0)
            emit diselected(this);
        if(value.toInt() == 1)
            emit selected(this);
    }
    return value;
}

void Entity::removeSelf()
{
    blockSignals(true);
    mRemove = true;
    this->deleteLater();
}
